package main

import (
	"flag"
	"fmt"
	"os/exec"
	"runtime"
)

func main() {
	port := flag.String("p", "8080", "端口")
	status := flag.String("s", "open", "open or close")
	flag.Parse()
	if *status == "open" {
		openPort(*port)
	} else if *status == "close" {
		closePort(*port)
	}
}

func openPort(port string) {
	system := runtime.GOOS
	if system == "linux" { //linux开端口
		cmd := exec.Command("firewall-cmd", "--permanent", "--zone=public", "--add-port="+port+"/tcp")
		err := cmd.Run()
		if err != nil {
			fmt.Println("Error opening port ", port, err)
		} else {
			fmt.Println("Port " + port + " opened successfully")
		}
		// 重启firewalld以应用更改
		restartFirewallCmd := exec.Command("firewall-cmd", "--reload")
		err = restartFirewallCmd.Run()
		if err != nil {
			fmt.Println("Error restarting firewalld:", err)
		} else {
			fmt.Println("firewalld restarted successfully")
		}
	} else if system == "windows" { //windows 开端口
		//清除端口原逻辑
		cmdBefore := exec.Command("netsh", "advfirewall", "firewall", "delete", "rule", "name=BlockPort"+port)
		output, err := cmdBefore.CombinedOutput()
		if err != nil {
			fmt.Println("cmdBefore.CombinedOutput err", err)
		}
		//执行新逻辑
		cmd := exec.Command("netsh", "advfirewall", "firewall", "add", "rule", "name=OpenPort"+port, "dir=in", "action=allow", "protocol=TCP", "localport="+port)
		output, err = cmd.CombinedOutput()
		if err != nil {
			fmt.Printf("Error opening port %s: %s\n", port, err)
		} else {
			fmt.Printf("Port %s opened successfully. Output: %s\n", port, output)
		}
	}
}

func closePort(port string) {
	//time.Sleep(30 * time.Second)
	system := runtime.GOOS
	if system == "linux" {
		cmd := exec.Command("firewall-cmd", "--permanent", "--zone=public", "--remove-port="+port+"/tcp")
		err := cmd.Run()
		if err != nil {
			fmt.Println("Error closing port ", port, err)
		} else {
			fmt.Println("Port " + port + " closed successfully")
		}
		// 重启firewalld以应用更改
		restartFirewallCmd := exec.Command("firewall-cmd", "--reload")
		err = restartFirewallCmd.Run()
		if err != nil {
			fmt.Println("Error restarting firewalld:", err)
		} else {
			fmt.Println("firewalld restarted successfully")
		}
	} else if system == "windows" {
		//
		cmdBefore := exec.Command("netsh", "advfirewall", "firewall", "delete", "rule", "name=OpenPort"+port)
		output, err := cmdBefore.CombinedOutput()
		if err != nil {
			fmt.Println("cmdBefore.CombinedOutput err", err)
		}

		cmd := exec.Command("netsh", "advfirewall", "firewall", "add", "rule", "name=BlockPort"+port, "dir=in", "action=block", "protocol=TCP", "localport="+port)
		output, err = cmd.CombinedOutput()
		if err != nil {
			fmt.Printf("Error closing port %s: %s\n", port, err)
		} else {
			fmt.Printf("Port %s closed successfully. Output: %s\n", port, output)
		}
	}
}
